const fs = require("fs");
const path = require("path");
const crypto = require("crypto");

function calculateMD5(str) {
  const hash = crypto.createHash("md5");
  hash.update(str);
  return hash.digest("hex");
}

const getDownloadName = (taskid) => {
  // const md5Hash = calculateMD5(szRemoteFilename);
  const downloadName = `${taskid}.download`;
  // const downloadName = `${md5Hash}.${taskid}.download`;
  // const downloadName = `${taskid}.download`;
  return downloadName;
};

const deleteTmpDownloadFile = async ({ downloadDirectory, taskid }) => {
  const fileName = getDownloadName(taskid);
  const tmpFullPath = path.join(downloadDirectory, fileName);

  // eslint-disable-next-line no-async-promise-executor
  return new Promise(async (resolve, reject) => {
    const isExists = await checkIfExists(tmpFullPath);
    if (!isExists) {
      return;
    }
    fs.unlink(tmpFullPath, (err) => {
      if (err) {
        reject(err);
      } else {
        resolve(`Successfully deleted ${tmpFullPath}`);
      }
    });
  });
};

const setRenameDownloadFile = ({ downloadDirectory, taskid, name }) => {
  let finalPath = null;
  try {
    const fileName = getDownloadName(taskid);
    const tmpFullPath = path.join(downloadDirectory, fileName);
    finalPath = path.join(downloadDirectory, name);

    let index = 0; // 初始为0，如果文件已存在则会进入循环并加1
    let newName = name;

    while (fs.existsSync(finalPath)) {
      const ext = path.extname(name);
      const base = path.basename(name, ext);
      if (index === 0) {
        newName = `${base}(1)${ext}`;
      } else {
        newName = `${base}(${index + 1})${ext}`; // index从0开始，所以这里需要+1
      }
      index++;
      finalPath = path.join(downloadDirectory, newName);
    }

    fs.renameSync(tmpFullPath, finalPath);
  } catch (error) {
    finalPath = null;
  }

  return finalPath;
};

function checkIfExists(path) {
  return new Promise((resolve, reject) => {
    fs.access(path, fs.constants.F_OK, (err) => {
      if (err) {
        if (err.code === "ENOENT") {
          resolve(false); // 文件或目录不存在
        } else {
          reject(err); // 其他错误
        }
      } else {
        resolve(true); // 文件或目录存在
      }
    });
  });
}

module.exports = {
  getDownloadName,
  deleteTmpDownloadFile,
  setRenameDownloadFile,
};
